<template>
  <div class="title-index">
    <div class="month">
      <ul class="tabs">
        <li
          class="li-tab"
          v-for="(item, index) in tabsParam"
          :key="index"
          :class="{ active: index === nowIndex }"
          @click="toggleTabs(index)"
        >
          {{ item }}
        </li>
      </ul>
    </div>
    <div class="get-time" v-if="tateData && tateData.length">
      <p>
        已选时间：{{ tateData[0] }} 至 {{ tateData[1] }}
      </p>
    </div>
    <el-button
      :icon="Download"
      class="right-el-button"
      @click="handleExport"
      >数据导出</el-button
    >
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from 'vue';
import { Download } from '@element-plus/icons-vue'; // 导入 Element Plus 图标
import { ElMessage, ElMessageBox } from 'element-plus';
import { exportReport } from '@/api/report'; // 导入新的 API 函数

// --- 1. 定义 Props 和 Emits ---
const props = defineProps<{
  flag: number,
  tateData: string[],
}>();

const emit = defineEmits(['sendTitleInd']); // 定义要触发的事件

// --- 2. 状态管理 (Refs) ---
const nowIndex = ref(props.flag - 1); // 根据 prop 初始化
const tabsParam = ['昨日', '近7日', '近30日', '本周', '本月'];

// --- 3. 监听 Props 变化 (替代 @Watch) ---
watch(() => props.flag, (newVal) => {
  nowIndex.value = newVal - 1;
});

// --- 4. 方法 (Functions) ---

// tab 切换
const toggleTabs = (index: number) => {
  nowIndex.value = index;
  // 触发事件，将 index + 1 (即 1, 2, 3, 4, 5) 发送给父组件
  emit('sendTitleInd', index + 1);
};

// 数据导出
const handleExport = () => {
  ElMessageBox.confirm('是否确认导出最近30天运营数据?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      const response = await exportReport();
      // response 是一个 Blob 对象
      const url = window.URL.createObjectURL(response);
      const a = document.createElement('a');
      a.href = url;
      a.download = '运营数据统计报表.xlsx';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);
      ElMessage.success('导出成功！');
    } catch (error) {
      ElMessage.error('导出失败');
    }
  }).catch(() => {
    // 用户点击取消
  });
};
</script>

<style lang="scss" scoped>
/* 在这里添加或迁移你的 title-index 组件的样式 */
.title-index {
  display: flex;
  align-items: center;
  border-radius: 4px;
  margin-bottom: 20px;
}
.tabs {
  display: flex;
  list-style: none;
  padding: 0;
  margin: 0;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  .li-tab {
    padding: 8px 20px;
    cursor: pointer;
    border-right: 1px solid #dcdfe6;
    &:last-child {
      border-right: none;
    }
    &.active {
      background-color: var(--el-color-primary);
      color: #fff;
    }
  }
}
.get-time {
  margin-left: 20px;
  font-size: 14px;
  color: #606266;
}
.right-el-button {
  margin-left: auto; // 将按钮推到最右边
}
</style>
